package com.mikao.service.impl;

import com.mikao.config.CdnProperties;
import com.mikao.dao.ServiceDao;
import com.mikao.dto.bo.ReqDataTableDto;
import com.mikao.dto.bo.ServiceForm;
import com.mikao.dto.vo.RspDataTableDto;
import com.mikao.service.ServiceService;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.util.ObjectUtils;
import org.springframework.web.multipart.MultipartFile;

import java.io.File;
import java.io.IOException;
import java.util.List;
import java.util.UUID;

/**
 * @author kenny
 */

@Service
public class ServiceServiceImpl implements ServiceService {

    @Value("${cdn.baseUrl}")
    private String cdn;
    private ServiceDao serviceDao;
    private final CdnProperties cdnProperties;

    public ServiceServiceImpl(ServiceDao serviceDao, CdnProperties cdnProperties) {
        this.serviceDao = serviceDao;
        this.cdnProperties = cdnProperties;
    }

    @Override
    public RspDataTableDto<com.mikao.entity.Service> serviceList(ReqDataTableDto reqDataTableDto) {
        List<com.mikao.entity.Service> list = serviceDao.findAll();
        return new RspDataTableDto<>(reqDataTableDto.getDraw(), (long) list.size(), list);
    }

    @Override
    public Boolean addService(ServiceForm serviceForm) {
        com.mikao.entity.Service service;
        if (ObjectUtils.isEmpty(serviceForm.getIdEdit())) {
            service = new com.mikao.entity.Service();
            BeanUtils.copyProperties(serviceForm, service);

            MultipartFile file = serviceForm.getImageUrl();
            File f = new File(cdnProperties.getBasePath());
            if (!f.exists()) {
                f.mkdirs();
            }

            String oldName = file.getOriginalFilename();
            String newName = UUID.randomUUID().toString() + oldName.substring(oldName.lastIndexOf("."));

            File newFile = new File(f.getAbsolutePath(), newName);
            try {
                newFile.createNewFile();
                file.transferTo(newFile);
            } catch (IOException e) {
                e.printStackTrace();
            }
            service.setImageUrl(cdn + newName);
        } else {
            service = serviceDao.findOne(serviceForm.getIdEdit());
            service.setName(serviceForm.getNameEdit());
            service.setVxCode(serviceForm.getVxCodeEdit());
        }
        serviceDao.saveAndFlush(service);
        return true;
    }

    @Override
    public void deleteService(Long id) {
        serviceDao.delete(id);
    }
}
